document.addEventListener('DOMContentLoaded', function () {
  // document.querySelector('body').style.backgroundColor = 'red'

  // chrome.extension.onMessage.addListener(
  //   function (request, sender, sendResponse) {
  //     console.log('>>> Request: ', request)
  //     console.log('>>> Sender: ', sender)
  //     loadScriptString(request.script)
  //   });
  let _urlKey = location.href.split('?')[0].split('//').pop().split('/')[0]
  chrome.storage.sync.get(_urlKey, (r) => {
    let res = r[_urlKey]
    if (!res || Object.keys(res).length < 1) {
      // 无脚本
    } else if (Object.prototype.toString.call(res) == '[object String]') {
      __loadJS(res)
    } else if (Object.prototype.toString.call(res) == '[object Array]') {
      loadJSBatch(res.filter(item => item.active).map(item => item.url))
    }
  })

}, true)

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

  if (request.url) {
    __loadJS(request.url)
  } else {
    loadScriptString(request.script)
  }
  sendResponse({ response: true })
})

function __loadJS (url) {
  return new Promise((resolve) => {
    if (document.querySelector('#append_us_url')) {
      document.getElementsByTagName("body")[0].removeChild(document.querySelector('#append_us_url'))
    }
    var script = document.createElement('script')
    script.id = 'append_us_url'
    script.type = "text/javascript"
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null
          resolve(true)
        }
      }
    } else {
      script.onload = function () {
        resolve(true)
      }
    }
    script.src = url
    document.body.appendChild(script)
  })
}

function loadJSBatch (scripts) {
  return new Promise(async (resolve) => {
    if (!scripts || (scripts.length == 0)) return resolve(true)
    if (Object.prototype.toString.call(scripts) == '[object String]') {
      await __loadJS(scripts)
      return resolve(true)
    }
    let _scripts = []
    for (let i = 0; i < scripts.length; i++) {
      _scripts.push(__loadJS(scripts[i]))
    }
    await Promise.all(_scripts)
    return resolve(true)
  })
}

function __loadCSS (url) {
  return new Promise((resolve) => {
    var style = document.createElement('link')
    style.rel = "stylesheet"
    if (style.readyState) {
      style.onreadystatechange = function () {
        if (style.readyState == "loaded" || style.readyState == "complete") {
          style.onreadystatechange = null
          resolve()
        }
      }
    } else {
      style.onload = function () {
        resolve()
      }
    }
    style.href = url
    document.head.appendChild(style)
  })
}

function loadScriptString (code) {
  if (document.querySelector('#append_us'))
    document.getElementsByTagName("body")[0].removeChild(document.querySelector('#append_us'))
  var script = document.createElement("script");
  script.id = 'append_us'
  script.type = "text/javascript";
  try {
    // firefox、safari、chrome和Opera
    script.appendChild(document.createTextNode(code));
  } catch (ex) {
    // IE早期的浏览器 ,需要使用script的text属性来指定javascript代码。
    script.text = code;
  }
  document.getElementsByTagName("body")[0].appendChild(script);
}